<template>
  <div
    class="chart-wrapper"
    :style="`--height:${typeof height === 'string' ? height : `${height}px`};`"
  >
    <div :id="chartId" class="chart-body" />
  </div>
</template>

<script setup>
import * as Echarts from 'echarts'
import { computed, onMounted, watch } from 'vue'
import { loadingOptions, defaultChartLineOptions } from './constant'

const props = defineProps({
  chartId: {
    type: String,
    required: true,
  },
  height: {
    type: [String, Number],
    default: '100%',
  },
  data: {
    type: Array,
    default: () => [],
  },
  options: {
    type: Object,
    default: () => ({}),
  },
})

let chart = null

const defaultSeries = {
  type: 'line',
  symbolSize: 2,
}

const chartOptions = computed(() => {
  return Object.deepAssign(defaultChartLineOptions, props.options)
})
watch(chartOptions, updateChart)

onMounted(() => {
  initChart(true)
})

function initChart(loading) {
  if (!chart && document.querySelector(`#${props.chartId}`)) {
    chart = Echarts.init(document.querySelector(`#${props.chartId}`))
  }
  if (loading && chart) {
    chart.setOption(loadingOptions)
  }
}

function updateChart(options) {
  if (!chart && document.querySelector(`#${props.chartId}`)) {
    chart = Echarts.init(document.querySelector(`#${props.chartId}`))
  }
  if (chart) {
    chart.clear()
    // console.log(options)
    chart.setOption(options, true)
  }
}
</script>

<style lang="less" scoped>
.chart-wrapper {
  height: var(--height);
  display: flex;
  flex-direction: column;
  .chart-body {
    flex: 1;
  }
}
</style>
